/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.servicebus;

import java.io.IOException;
import java.util.Properties;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Property;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Updated;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.iosgi.util.Network;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sven Schulz
 */
@Component(immediate = true)
public class ZookeeperServer implements Runnable {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(ZookeeperServer.class);

	@Property(name = "tickTime", value = "2000")
	private long tickTime;

	@Property(name = "initLimit", value = "10")
	private long initLimit;

	@Property(name = "syncLimit", value = "5")
	private long syncLimit;

	@Property(name = "dataDir")
	private String dataDir;

	@Property(name = "clientPort", value = "2181")
	private int clientPort;

	@Property(name = "maxClientCnxns", value = "0")
	private int maxClientConnections;

	@Requires
	private Network network;

	private ZkMain main;
	private ServerConfig config;
	private Thread zkThread;

	public ZookeeperServer(BundleContext context) throws IOException {
		dataDir = context.getDataFile("zk-data").getCanonicalPath();
	}

	@Invalidate
	public void destroy() throws InterruptedException {
		shutdown();
	}

	@Updated
	void reconfigure() throws IOException, ConfigException,
			InterruptedException {
		shutdown();
		Properties p = new Properties();
		p.setProperty("tickTime", Long.toString(tickTime));
		p.setProperty("initLimit", Long.toString(initLimit));
		p.setProperty("syncLimit", Long.toString(syncLimit));
		p.setProperty("dataDir", dataDir);
		p.setProperty("clientPort", Integer.toString(clientPort));
		p.setProperty("maxClientCnxns", Integer.toString(maxClientConnections));
		p.setProperty("clientPortAddress", network.getAddress()
				.getHostAddress());
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("starting zookeeper server on {}:{}",
					p.get("clientPortAddress"), p.get("clientPort"));
		}
		QuorumPeerConfig qpc = new QuorumPeerConfig();
		qpc.parseProperties(p);
		config = new ServerConfig();
		config.readFrom(qpc);
		zkThread = new Thread(this);
		zkThread.start();
	}

	@Override
	public void run() {
		main = new ZkMain();
		try {
			main.runFromConfig(config);
		} catch (IOException ioe) {
			LOGGER.error("attempt to run zookeeper server failed", ioe);
		}
	}

	public void shutdown() throws InterruptedException {
		if (main != null) {
			main.shutdown();
			zkThread.join();
		}
	}

	static class ZkMain extends ZooKeeperServerMain {
		@Override
		protected void shutdown() {
			super.shutdown();
		}
	}

}